import React, { useState, useEffect } from "react";
import { Form, Input, Modal, Row, Col, InputNumber } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack';
import { exportSheetTable } from "@/utils/exportTable";
import { apiStockPurchaseView, apiAddStockInLibrary } from "@/request/procurement";
import { limitInteger } from "@/utils/numberFixed2";
import _ from "lodash";
const { Search } = Input
const ProcureAdd = (props) => {
  const [Purchase, setPurchase] = useState(null);
  const [isSave, onSave] = useState(false);
  const [library, setLibraryName] = useState();
  const [supplier, setSupplierName] = useState();
  const [libraryId, setLibraryId] = useState(null);
  const [supplierId, setSupplierId] = useState(null);
  const [dataSource, setDataSource] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [wareData, setWareData] = useState([]);
  const [request, setRequest] = useState();
  const [change, setChange] = useState();
  const [searchDataSource, setSearchDataSource] = useState([])
  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (text, record, index) => {
        return record.code === '合计' ? '' : index + 1;
      }
    },
    {
      title: "采购仓库",
      dataIndex: "libraryName",
      key: "libraryName",
    },
    {
      title: "供应商",
      dataIndex: "supplierName",
      key: "supplierName",
    },
    {
      title: "采购单号",
      dataIndex: "code",
      key: "code",
    },
    {
      title: "物品名称",
      dataIndex: "goodsName",
      key: "goodsName",
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      key: 'materialName'
    },
    {
      title: "物料编码",
      dataIndex: "goodsSkuNo",
      key: "goodsSkuNo",
    },
    {
      title: "规格名",
      dataIndex: "goodsSkuName",
      key: "goodsSkuName",
    },
    {
      title: "应收数量",
      dataIndex: "shouldInNum",
      key: "shouldInNum",
    },
    {
      title: "实收数量",
      dataIndex: "realInNum",
      key: "realInNum",
    },
    {
      title: "入库数量",
      dataIndex: "wareInNum",
      key: "wareInNum",
      render: (text, render, index) => {
        return render.code === '合计' ? <div>{text}</div> : <div>
          <InputNumber haspermi={['procurement:details:delet']}
            min={0} precision={0}
            value={text}
            formatter={limitInteger}
            onChange={(e, id) => { onChangeNum(e, render.id) }}
          />
        </div>
      }
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
      render: (text, render, index) => {
        return render.code === '合计' ? null : <div>
          <Input value={text} maxLength={100} onChange={(e, id) => { onChangeRemark(e, render.id) }} />
        </div>
      }
    },
  ]
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setWareData(selectedRows)
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: (record) => ({ disabled: record.code === '合计' })
  };
  useEffect(() => {
    apiStockPurchaseView({ id: props.match.params.id }).then(
      (res) => {
        if (res.code === 0 && res.data) {
          if (res.data.status === 2) {
            onSave(true)
          }
          let shouldInNumTotal = 0
          let realInNumTotal = 0
          let data = _.dropRight(res.data.stockPurchaseDetailsVos)
          data.map((item) => {
            console.log(item);
            shouldInNumTotal += item.shouldInNum
            realInNumTotal += item.realInNum
          })
          data.push(
            {
              code: '合计',
              shouldInNum: shouldInNumTotal,
              realInNum: realInNumTotal,
              wareInNum: "0"
            }
          )
          console.log(data);
          setSearchDataSource(data)
          setPurchase(res.data)
          setDataSource(data)
          setLibraryName(res.data.libraryName)
          setSupplierName(res.data.supplierName)
          setLibraryId(res.data.libraryId)
          setSupplierId(res.data.supplierId)
        }
      }
    )
  }, [])
  useEffect(() => {
    apiStockPurchaseView({ id: props.match.params.id }).then(
      (res) => {
        if (res.code === 0 && res.data) {
          if (res.data.status === 2) {
            onSave(true)
          }
          let shouldInNumTotal = 0
          let realInNumTotal = 0
          let data = _.dropRight(res.data.stockPurchaseDetailsVos)
          data.map((item) => {
            shouldInNumTotal += item.shouldInNum
            realInNumTotal += item.realInNum
          })
          data.push(
            {
              code: '合计',
              shouldInNum: shouldInNumTotal,
              realInNum: realInNumTotal,
              wareInNum: "0"
            }
          )
          setPurchase(res.data)
          setSearchDataSource(data)
          setLibraryName(res.data.libraryName)
          setSupplierName(res.data.supplierName)
          setLibraryId(res.data.libraryId)
          setSupplierId(res.data.supplierId)
          setWareData([])
        }
      }
    )
  }, [request])
  let onChangeNum = (e, id) => {
    let newdataSource = searchDataSource
    let len = searchDataSource.length
    let last = len - 1
    newdataSource[last].wareInNum = 0
    for (let i = 0; i < len; i++) {
      if (newdataSource[i].id === id) {
        newdataSource[i].wareInNum = e
      }
    }
    for (let j = 0; j < last; j++) {
      if (newdataSource[j].hasOwnProperty('wareInNum')) {
        newdataSource[last].wareInNum += newdataSource[j].wareInNum
      }
    }
    setSearchDataSource([...newdataSource])
  }
  let onChangeRemark = (e, id) => {
    let newdataSource = searchDataSource
    let len = searchDataSource.length
    for (let i = 0; i < len; i++) {
      if (newdataSource[i].id === id) {
        newdataSource[i].remark = e.target.value
      }
    }
    setSearchDataSource([...newdataSource])
  }
  let createProcurement = () => {
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '请核对数量信息是否生成入库单？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        if (wareData.length > 0 && selectedRowKeys.length > 0) {
          for (let i = 0; i < wareData.length; i++) {
            if (!wareData[i].wareInNum) {
              React.$message({
                type: 'warning',
                content: '请填写入库数量'
              })
              return
            }
          }
          let params = {
            dataType: 1,
            stockPurchaseDetails: wareData,
            stockPurchaseNote: {
              id: Purchase.id,
              libraryId: libraryId,
              supplierId: supplierId,
            },
          }
          await apiAddStockInLibrary({ ...params }).then(
            (res) => {
              if (res.code === 0) {
                React.$message({
                  type: 'info',
                  content: '入库成功'
                })
                setSelectedRowKeys([])
                setRequest(res)
              } else {
                setSelectedRowKeys([])
                setRequest(res)
              }
            }
          )
        } else {
          React.$message({
            type: 'warning',
            content: '请先勾选入库商品'
          })
        }
      }
    });
  }
  let setSearchValue = (value) => {
    let search = value.target.value.trim()
    if (search) {
      getSearchData(dataSource, search)
    } else {
      setSearchDataSource(dataSource)
    }
  }
  let getSearchData = (aim, searchVal) => {
    let newArr = []
    for (var i = 0; i < aim.length; i++) {
      let value = aim[i].goodsSkuNo
      if (value && value.includes(searchVal)) {
        newArr.push(aim[i]);//将值放入第二个数组
      }
    }
    let shouldInNumTotal = 0
    let realInNumTotal = 0
    newArr.map((item) => {
      console.log(item);
      shouldInNumTotal += item.shouldInNum
      realInNumTotal += item.realInNum
    })
    newArr.push(
      {
        code: '合计',
        shouldInNum: shouldInNumTotal,
        realInNum: realInNumTotal,
        wareInNum: "0"
      }
    )
    setSearchDataSource(newArr)
  }
  // 导出
  let exportGoods = (e) => {
    let tH_data = [
      {
        title: `${library}-采购入库单详情(供应商:${supplier})`,
        prop: '',
        children: [
          { prop: 'libraryName', title: '采购仓库' },
          { prop: 'supplierName', title: '供应商' },
          { prop: 'code', title: '采购单号' },
          { prop: 'materialName', title: '物料名称' },
          { prop: 'goodsSkuNo', title: '物料编码' },
          { prop: 'goodsSkuName', title: '规格名' },
          { prop: 'shouldInNum', title: '应收数量', valueType: 'number' },
          { prop: 'realInNum', title: '实收数量', valueType: 'number' },
        ]
      }
    ]
    let code = dataSource[0].code;
    let tB_data = dataSource.map(item => {
      return {
        libraryName: item.libraryName,
        supplierName: item.supplierName,
        code: item.code,
        materialName: item.materialName,
        goodsSkuNo: item.goodsSkuNo,
        goodsSkuName: item.goodsSkuName,
        shouldInNum: item.shouldInNum,
        realInNum: item.realInNum,
      }
    })
    exportSheetTable({
      fileName: `${library}-采购入库单详情-${code}`, tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false
    })
  }

  return (
    <div className="p-layout-box">
      <GoBack history={props.history} title="采购入库单详情" />
      <Form
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 18,
        }}

        style={{ marginBottom: 12, marginTop: 12 }}>
        <Row>
          <Search
            placeholder="请输入物料编码"
            onChange={(e) => setSearchValue(e)}
            style={{
              width: 200,
            }}
            allowClear
          />
          <Col span={8}>
            <Form.Item name={"libraryId"} label="采购仓库"
              rules={[{ required: true }]} >
              <div >
                {library}
              </div>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name={"supplierId"} label="供应商"
              rules={[{ required: true }]} >
              {supplier}
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div style={{ marginBottom: 12 }}>
        {
          !isSave ?
            <span style={{ marginRight: 10 }}>
              <TheButton haspermi={['procurement:warehouse:add']} onClick={createProcurement} size="middle" type="primary">生成入库单</TheButton>
            </span> : <div></div>
        }
        {
          <TheButton onClick={() => exportGoods(true)} type="dashed" size="middle">导出</TheButton>
        }
      </div>
      <TheTable
        rowSelection={rowSelection}
        scroll={{ x: "max-content", y: '63vh' }}
        columns={columns}
        dataSource={searchDataSource}
        rowKey={record => record.id}
      />
    </div>
  );
}

export default ProcureAdd